# -*- coding: utf-8 -*-
import jenkins
import xml.etree.ElementTree as ET
import json
import sys
import os


curPath = os.path.split(sys.argv[0])[0]
jenkinsUrl = sys.argv[1]
jenkinsUsername = sys.argv[2]
jenkinsPassword = sys.argv[3]
jenkinsJobName = sys.argv[4]
projectName = sys.argv[5]
gameNames = sys.argv[6]
platform = sys.argv[7]

projectConfigPath = os.path.join(curPath, "projectConfig.json")

gameConfig = None


def get_game_config():
    with open(projectConfigPath) as c:
        cf = json.load(c)
        global gameConfig
        gameConfig = cf[projectName]["ProjectConfig"][platform]


def begin_build_job():
    jenkinsServer = jenkins.Jenkins(jenkinsUrl, username=jenkinsUsername, password=jenkinsPassword)
    config = jenkinsServer.get_job_config(jenkinsJobName)
    root = ET.fromstring(config)
    customWorkspace = root.find('customWorkspace')
    customWorkspace.text = gameConfig["customWorkspace"]
    newJobConfig = ET.tostring(root, encoding="unicode")
    jenkinsServer.reconfig_job(jenkinsJobName, newJobConfig)
    gameConfig["GameNames"] = gameNames
    gameConfig["ProjectName"] = projectName
    jenkinsServer.build_job(jenkinsJobName, gameConfig)


if __name__ == "__main__":
    get_game_config()
    begin_build_job()
